package cn.pconline.autoclub.util.dyna;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommentDynaUtils {
	public static final String URL_PATTERN = "http://[\\w\\.\\-/:=\\?\\&\\%\\#]+|www\\.[\\w\\.\\-/:=\\?\\&\\%\\#]+";
	public static final String[] suffixs = {".com", ".cn"};
	
	public static String appendUrlUBB(String content) {
		Pattern p = Pattern.compile(URL_PATTERN);
		Matcher m = p.matcher(content);
		List<String> list = new ArrayList<String>();
		while (m.find()) {
			String tmp = m.group();
			if (tmp.startsWith("www")) {
				if (isContainsSuffix(tmp)) {
					list.add(tmp);
				}
			} else {
				list.add(tmp);
			}
		}
		
		if (list.isEmpty()) {
			return content;
		}
		
		int i = 0;
		for (String s : list) {
			content = content.replace(s, "{"+(i++)+"}");
		}
		i = 0;
		for (String s: list) {
			content = content.replace("{"+(i++)+"}", appendUBB(s));
		}
		return content;
	}
	
	private static boolean isContainsSuffix(String content) {
		for (String s : suffixs) {
			if (content.contains(s)) {
				return true;
			}
		}
		return false;
	}
	
	private static String appendUBB(String url) {
		return new StringBuilder()
			.append("[url]").append(url.startsWith("http://")?url:("http://")+url).append("[/url]").toString();
	}
	
}
